import { _decorator, Component } from 'cc';
import { EvolutionNode } from './EvolutionNode';
import { GameEvents } from '../constants/GameConstants';
import { EventManager } from '../core/EventManager';

const { ccclass, property } = _decorator;

/**
 * 水生生物进化树
 * 
 * 功能：
 * 1. 定义水生生物进化路线
 * 2. 管理水生进化节点
 * 3. 处理水生特殊能力
 * 4. 提供水下适应性
 * 
 * 特点：
 * 1. 水下呼吸能力
 * 2. 游泳速度提升
 * 3. 深海压力适应
 * 4. 水下感知能力
 */
@ccclass('AquaticEvolutionTree')
export class AquaticEvolutionTree extends Component {
    private evolutionNodes: Map<string, EvolutionNode> = new Map();
    private currentStage: string = 'basic_aquatic';

    onLoad() {
        this.initEvolutionTree();
    }

    private initEvolutionTree() {
        // 基础水生生物
        this.addEvolutionNode('basic_aquatic', {
            name: '基础水生生物',
            description: '适应水生环境的基础形态',
            requirements: [],
            effects: {
                swimSpeed: 8,
                waterBreathing: 1,
                underwaterVision: 10
            },
            skills: ['basic_swim']
        });

        // 深海适应者
        this.addEvolutionNode('deep_diver', {
            name: '深海适应者',
            description: '能够在深海环境生存',
            requirements: ['basic_aquatic'],
            effects: {
                pressureResistance: 20,
                darkVision: 15,
                swimSpeed: 12
            },
            skills: ['pressure_adapt', 'dark_sense']
        });

        // 敏捷游者
        this.addEvolutionNode('swift_swimmer', {
            name: '敏捷游者',
            description: '高速水中移动能力',
            requirements: ['basic_aquatic'],
            effects: {
                swimSpeed: 20,
                agility: 15,
                acceleration: 10
            },
            skills: ['rapid_swim', 'water_dash']
        });

        // 海洋掠食者
        this.addEvolutionNode('ocean_hunter', {
            name: '海洋猎手',
            description: '顶级水生掠食者',
            requirements: ['swift_swimmer'],
            effects: {
                attack: 25,
                huntingVision: 20,
                ambushPower: 15
            },
            skills: ['water_ambush', 'sonic_wave']
        });

        // 深海巨兽
        this.addEvolutionNode('abyssal_titan', {
            name: '深渊泰坦',
            description: '统治深海的巨型生物',
            requirements: ['deep_diver'],
            effects: {
                size: 3,
                health: 400,
                pressureResistance: 50,
                intimidation: 25
            },
            skills: ['pressure_burst', 'tidal_force']
        });

        // 珊瑚共生者
        this.addEvolutionNode('coral_symbiote', {
            name: '珊瑚共生者',
            description: '与珊瑚礁建立共生关系',
            requirements: ['basic_aquatic'],
            effects: {
                regeneration: 10,
                camouflage: 15,
                reefAffinity: 20
            },
            skills: ['coral_heal', 'reef_blend']
        });
    }

    private addEvolutionNode(id: string, config: EvolutionNodeConfig) {
        const node = new EvolutionNode(id, config);
        this.evolutionNodes.set(id, node);
    }

    public canEvolve(targetStage: string): boolean {
        const node = this.evolutionNodes.get(targetStage);
        if (!node) return false;

        // 检查是否满足前置条件
        return node.requirements.every(req => {
            const reqNode = this.evolutionNodes.get(req);
            return reqNode?.isUnlocked;
        });
    }

    public evolve(targetStage: string): boolean {
        if (!this.canEvolve(targetStage)) return false;

        const node = this.evolutionNodes.get(targetStage);
        if (!node) return false;

        // 解锁进化节点
        node.unlock();
        this.currentStage = targetStage;

        // 应用进化效果
        this.applyEvolutionEffects(node);

        // 发送进化完成事件
        EventManager.instance.emit(GameEvents.EVOLUTION_COMPLETE, {
            stage: targetStage,
            effects: node.effects,
            type: 'aquatic'
        });

        return true;
    }

    private applyEvolutionEffects(node: EvolutionNode) {
        // 应用属性效果
        const character = this.node.getComponent('CharacterStats');
        if (character) {
            Object.entries(node.effects).forEach(([stat, value]) => {
                character.modifyStat(stat, value);
            });
        }

        // 解锁技能
        const skillManager = this.node.getComponent('SkillManager');
        if (skillManager) {
            node.skills.forEach(skillId => {
                skillManager.unlockSkill(skillId);
            });
        }

        // 应用特殊水生效果
        this.applyAquaticEffects(node);
    }

    private applyAquaticEffects(node: EvolutionNode) {
        // 处理水生特有属性
        if (node.effects.waterBreathing) {
            this.enableWaterBreathing(node.effects.waterBreathing);
        }
        if (node.effects.pressureResistance) {
            this.enablePressureResistance(node.effects.pressureResistance);
        }
        if (node.effects.underwaterVision) {
            this.enhanceUnderwaterVision(node.effects.underwaterVision);
        }
    }

    private enableWaterBreathing(level: number) {
        const waterBreathing = this.node.getComponent('WaterBreathing');
        if (waterBreathing) {
            waterBreathing.setLevel(level);
        }
    }

    private enablePressureResistance(level: number) {
        const pressureResistance = this.node.getComponent('PressureResistance');
        if (pressureResistance) {
            pressureResistance.setLevel(level);
        }
    }

    private enhanceUnderwaterVision(level: number) {
        const underwaterVision = this.node.getComponent('UnderwaterVision');
        if (underwaterVision) {
            underwaterVision.setLevel(level);
        }
    }

    public getCurrentStage(): string {
        return this.currentStage;
    }

    public getEvolutionNode(stage: string): EvolutionNode | undefined {
        return this.evolutionNodes.get(stage);
    }
} 